<template>
  <t-dialog
    :header="`${header}-${isEdit ? '修改人员' : '添加人员'}`"
    :visible.sync="visible"
    :onClose="closeDialog"
    :closeOnOverlayClick="false"
    confirmBtn="确定"
    :onConfirm="onSubmit"
    width="80%"
    top="1%"
  >
    <div id="main">
      <t-loading text="加载中..." :fullscreen="false" attach="#main" :loading="applyLoading" size="medium"> </t-loading>
      <div>
        <!-- 基本信息 -->
        <t-form ref="form" :data="formData" :rules="rules" labelWidth="180px">
          <t-row style="align-items: stretch; width: 99%" :gutter="14">
            <t-col :span="12">
              <t-card size="medium" title="基本信息">
                <t-row style="align-items: stretch" :gutter="14">
                  <t-col :span="6">
                    <t-form-item label="投入年份：" name="year">
                      <t-date-picker mode="year" style="width: 390px" v-model="formData.year"></t-date-picker>
                    </t-form-item>
                    <t-form-item label="姓名：" name="name">
                      <t-select
                        v-model="formData.name"
                        creatable
                        filterable
                        @change="onLeaderNameChange"
                        placeholder="请输入姓名"
                        :loading="leaderLoading"
                        @search="remoteProjectLeaderMethod"
                        :options="nameOptions"
                        @create="createProjectLeaderOptions"
                        style="width: 390px"
                      />
                    </t-form-item>
                    <t-form-item label="身份证号：" name="idCard">
                      <t-input
                        style="width: 390px"
                        @change="onIdCardChange"
                        placeholder="请输入身份证号"
                        clearable
                        v-model="formData.idCard"
                      ></t-input>
                    </t-form-item>
                    <t-form-item label="性别：" name="sex">
                      <t-select
                        style="width: 390px"
                        placeholder="请选择性别"
                        :options="dictTypes.sys_user_sex"
                        v-model="formData.sex"
                      >
                      </t-select>
                    </t-form-item>
                    <t-form-item label="出生年月：" name="birthDate">
                      <t-date-picker
                        placeholder="请选择生日"
                        mode="month"
                        v-model="formData.birthDate"
                        :disable-date="{
                          after: dayjs().endOf('month').add(-18, 'year').format(),
                        }"
                        style="width: 390px"
                      ></t-date-picker>
                    </t-form-item>
                    <t-form-item label="技术职称：" name="profTitId">
                      <t-tree-select
                        clearable
                        @change="onProfTitIdChange"
                        filterable
                        style="width: 390px"
                        :treeProps="{ keys: { value: 'id', label: 'name' }, valueMode: 'onlyLeaf' }"
                        v-model="formData.profTitId"
                        :data="profTitOptions"
                        placeholder="技术职称"
                      ></t-tree-select>
                      <!--                    <t-input style="width: 390px" clearable v-model="formData.projectLeader.profTitId"-->
                      <!--                    ></t-input>-->
                    </t-form-item>
                    <t-form-item label="职称：" name="profTit">
                      <t-select
                        disabled
                        style="width: 390px"
                        v-model="formData.profTit"
                        clearable
                        placeholder="请选择职称"
                        :options="dictTypes.prof_tit"
                      >
                      </t-select>
                    </t-form-item>
                    <t-form-item label="职务：" name="duty">
                      <t-input style="width: 390px" clearable v-model="formData.duty"></t-input>
                    </t-form-item>
                  </t-col>
                  <t-col :span="6">
                    <t-form-item label="所在单位名称：" name="company">
                      <t-tree-select
                        clearable
                        filterable
                        style="width: 390px"
                        :treeProps="{ keys: { value: 'label' } }"
                        v-model="formData.company"
                        :data="deptMenuOptions"
                        placeholder="选择工作单位"
                      ></t-tree-select>
                    </t-form-item>
                    <t-form-item label="是否为内部：" name="isInnerCompany">
                      <t-select
                        style="width: 390px"
                        v-model="formData.isInnerCompany"
                        clearable
                        placeholder="请选择是否为内部"
                        :options="[
                          { label: '是', value: '1' },
                          { label: '否', value: '0' },
                        ]"
                      >
                      </t-select>
                    </t-form-item>
                    <t-form-item label="学历：" name="education">
                      <t-select
                        style="width: 390px"
                        v-model="formData.education"
                        clearable
                        placeholder="请选择学历"
                        :options="dictTypes.education"
                      >
                      </t-select>
                    </t-form-item>
                    <t-form-item label="学位：" name="degree">
                      <t-select
                        style="width: 390px"
                        v-model="formData.degree"
                        clearable
                        placeholder="请选择学位"
                        :options="dictTypes.degree"
                      >
                      </t-select>
                    </t-form-item>
                    <t-form-item ref="reviseNum" label="是否获奖省部级人才称号：" name="sbjTitle">
                      <t-select
                        style="width: 390px"
                        v-model="formData.sbjTitle"
                        clearable
                        placeholder="请选择是否获奖省部级人才称号"
                        :options="[
                          { label: '是', value: '1' },
                          { label: '否', value: '0' },
                        ]"
                      >
                      </t-select>
                    </t-form-item>
                    <t-form-item ref="reviseNum" label="备注：" name="note">
                      <t-input style="width: 390px" clearable v-model="formData.note"></t-input>
                    </t-form-item>
                  </t-col>
                </t-row>
              </t-card>
            </t-col>
          </t-row>
        </t-form>
      </div>
    </div>
  </t-dialog>
</template>

<script>
import { getDictList } from '@/api/system/dict/data';
import { getFiles } from '@/api/common';

import { TODAY } from '@/utils/date';
import dayjs from 'dayjs';
import { getIdCardBirthday } from '@/utils/common';

export default {
  name: 'people-apply',
  components: {},
  dicts: ['formulate_type', 'standard_category', 'standard_property'],
  props: {
    header: String,
    objId: [String, Number],
    row: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      profTitOptions: [],
      deptMenuOptions: [],
      visible: true,
      dictTypes: {},
      nameOptions: [],
      leaderLoading: false,
      subBtnLoading: false,
      reviseNumDisable: true,
      active: 1,
      subType: 2,
      applyLoading: false,
      lengthLimitObj: {
        description: 0,
      },
      tinymceFlag: 1,
      dayjs,
      isEdit: false,
      formData: {
        id: Date.parse(new Date()),
        platformId: this.objId,
        year: '',
        name: '',
        idCard: '',
        sex: '',
        birthDate: '',
        profTitId: '',
        profTit: '',
        duty: '',
        company: '',
        isInnerCompany: '',
        degree: '',
        education: '',
        sbjTitle: '',
        note: '',
      },
      rules: {
        year: [
          {
            required: true,
            message: '投入时间不能为空',
          },
        ],
        name: [
          {
            required: true,
            message: '姓名不能为空',
          },
        ],
        idCard: [
          {
            required: true,
            message: '身份证号不能为空',
          },
          {
            message: '身份证号不正确',
            pattern:
              /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/,
          },
        ],
        sex: [
          {
            required: true,
            message: '性别不能为空',
          },
        ],
        birthDate: [
          {
            required: true,
            message: '出生年月不能为空',
          },
        ],
        profTitId: [
          {
            required: true,
            message: '职称不能为空',
          },
        ],
        profTit: [
          {
            required: true,
            message: '职称等级不能为空',
          },
        ],
        duty: [
          {
            required: true,
            message: '职务不能为空',
          },
        ],
        company: [
          {
            required: true,
            message: '所在单位名称不能为空',
          },
        ],
        isInnerCompany: [
          {
            required: true,
            message: '是否为内部不能为空',
          },
        ],
        degree: [
          {
            required: true,
            message: '学位不能为空',
          },
        ],
        education: [
          {
            required: true,
            message: '学历不能为空',
          },
        ],
        sbjTitle: [
          {
            required: true,
            message: '是否获奖省部级人才称号不能为空',
          },
        ],
      },
    };
  },
  async mounted() {
    await this.getDataTypes();
    this.isEdit = !!this.row.id
  },
  async created() {
    await this.getDeptTreeSelect(this.$store.state.user.deptId);
    await this.getProfTitTreeSelect();
    Object.assign(this.formData, this.row)
    // 判断路由有没有id传过来
    // 有id则是修改需要回显数据，无id则是新增
  },
  methods: {
    onProfTitIdChange(val, content) {
      this.formData.profTit = content.node.data.level;
    },
    getProfTitTreeSelect() {
      return this.$api.system.profTit
        .list()
        .then((response) => {
          this.profTitOptions = this.handleTree(response.data, 'id');
        })
        .catch((e) => {
          this.$message.error(e.toString());
        });
    },
    getDataTypes() {
      return getDictList([
        'project_type',
        'subject_classification',
        'sys_user_sex',
        'prof_tit',
        'degree',
        'education',
        'duty',
        'platform_type',
        'expect_result_type',
      ])
        .then((response) => {
          this.dictTypes = response.data;
        })
        .catch((e) => {
          this.$message.error(e.toString());
        });
    },
    onIdCardChange(val) {
      const birthday = getIdCardBirthday(val);
      if (birthday !== '') {
        this.formData.birthDate = birthday.slice(0, 7);
      }
    },
    onLeaderNameChange(val, content) {
      const index = this.nameOptions.findIndex((val) => content?.option?.id === val.id);
      this.nameOptions[index].label = this.nameOptions[index].name;
      this.$set(this.nameOptions, index, this.nameOptions[index]);
      // Object.assign(this.formData.projectLeader, content.option)
      const oldId = this.formData.id;
      let year = this.formData.year;
      Object.assign(this.formData, content.option || this.nameOptions[index]);
      // this.formData = content.option || this.nameOptions[index]
      this.formData.year = year;
      this.formData.id = oldId;
    },
    createProjectLeaderOptions(value) {
      this.nameOptions.push({
        label: `${value}`,
        value,
        name: value,
      });
    },
    remoteProjectLeaderMethod(search) {
      this.leaderLoading = true;
      this.$api.system.member
        .searchList({ name: search })
        .then((response) => {
          this.nameOptions = response.data.map((val) => ({
            ...val,
            label: `${val.name}-${val.idCard}`,
            value: `${val.name}-${val.idCard}`,
          }));
          this.leaderLoading = false;
        })
        .catch((e) => {
          this.leaderLoading = false;
          this.$message.error(e.toString());
        });
    },
    getDeptTreeSelect() {
      return this.$api.system.dept
        .treeSelectAllIn()
        .then((response) => {
          this.deptMenuOptions = response.data;
        })
        .catch((e) => {
          this.$message.error(e.toString());
        });
    },
    filterByTree(val, tree, children = 'children', id = 'id', label = 'label') {
      let text = '';
      const convert = (arr) => {
        arr.filter((item) => {
          if (item[id] === val) {
            text = item[label];
          } else if (item[children]) {
            return convert(item[children]);
          }
          return false;
        });
      };
      convert(tree);
      return text;
    },
    onSubmit() {
      this.$refs.form.validate().then(async (validateResult) => {
        if (validateResult === true) {
          // 路由有id修改，没有新增
          if (this.isEdit) {
            const message = '修改成功';
            this.subBtnLoading = true;
            this.$api.tjpt.people
              .edit(this.formData)
              .then((response) => {
                this.subBtnLoading = false;
                this.$message.success(message);
                this.$emit('reload');
                this.closeDialog()
              })
              .catch((e) => {
                this.subBtnLoading = false;
                this.$message.error(e.toString());
              });
          } else {
            const message = '提交成功';
            this.subBtnLoading = true;
            this.$api.tjpt.people
              .add(this.formData)
              .then((response) => {
                this.subBtnLoading = false;
                this.$message.success(message);
                this.$emit('reload');
                this.closeDialog()
              })
              .catch((e) => {
                this.subBtnLoading = false;
                this.$message.error(e.toString());
              });
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    closeDialog() {
      this.$emit('update:visible', false);
    },
  },
};
</script>

